<template>
	<view class="cart-container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content"
				:style="{ height: navBarHeight + 'px', paddingRight: (menuButtonInfo.width + menuButtonInfo.right - windowWidth + 10 + 20) + 'px' }">
				<view class="navbar-title">
					<text class="title-text">购物车</text>
				</view>
				<view class="navbar-right">
					<view class="edit-btn" @click="toggleEditMode">
						<text class="edit-text">{{ isEditMode ? '完成' : '编辑' }}</text>
					</view>
				<view class="message-btn" @click="goMessage">
					<u-icon name="bell" size="24" :color="hasNewMessage ? '#fff' : '#fff'"></u-icon>
					<view class="message-dot" v-if="hasNewMessage"></view>
				</view>
				</view>
			</view>
		</view>

		<!-- 空购物车提示 -->
		<view class="empty-cart" v-if="!isLoggedIn">
			<view class="empty-content">
				<view class="empty-text">
					<text>您还没有登录，</text>
					<text class="login-link" @click="goLogin">前去登录</text>
				</view>
			</view>
		</view>

		<view class="empty-cart" v-else-if="cartList.length === 0 && !loading">
			<view class="empty-content">
				<text class="empty-text">亲，您的购物车里还没有商品哦！</text>
				<text class="empty-desc">赶快去购买吧</text>
				<button class="go-shopping-btn" @click="goShopping">
					<text class="btn-text">去购买</text>
				</button>
			</view>
		</view>

		<!-- 购物车列表 -->
		<view class="cart-content" v-else>
			<!-- 商品列表 -->
			<scroll-view scroll-y class="cart-scroll">
				<!-- 商家分组 -->
				<view class="store-group" v-for="(store, storeIndex) in storeGroups" :key="store.manufac_id">
					<!-- 商家信息 -->
					<view class="store-header">
						<view class="store-select" @click="toggleSelectStore(store)">
							<view class="checkbox" :class="{ 'checked': store.isSelected }">
								<image v-if="store.isSelected" :src="serverAddress + 'img/qweqwe.png'" class="checkbox-icon"></image>
							</view>
						</view>
						<view class="store-info">
							<image v-if="store.file_path && store.file_path !== 'null'" :src="store.file_path" class="store-logo" @error="handleLogoError($event, store)"></image>
							<image v-else :src="serverAddress + 'img/icon-dianpu@2x.png'" class="store-logo-default"></image>
							<text class="store-name">{{ store.manufac_name }}</text>
						</view>
					</view>

					<!-- 商品列表 -->
					<view class="goods-item"
						:class="{ 'inshort': item.is_sale === 0 || (item.is_sale === 1 && item.count > item.stock) }"
						v-for="(item, itemIndex) in store.shop" :key="item.cart_goods_id">
						
						<!-- 左侧固定层 -->
						<view class="item-left-layer">
							<view class="item-select" @click="toggleSelectItem(item, store)">
								<view class="checkbox"
									:class="{ 'gchecked': item.isSelected, 'inshort': item.is_sale === 0 || (item.is_sale === 1 && item.count > item.stock) }">
									<image v-if="item.isSelected" :src="serverAddress + 'img/qweqwe.png'" class="checkbox-icon"></image>
								</view>
							</view>

							<view class="item-photo" @click="goProductDetail(item)">
								<image :src="item.file_path" class="goods-image"></image>
								<!-- 商品状态标签 -->
								<view class="status-tag" v-if="item.is_sale === 0">下架</view>
								<view class="status-tag" v-else-if="item.is_sale === 1 && item.count > item.stock">缺货</view>
							</view>
						</view>

						<!-- 右侧内容区域 -->
						<view class="item-right-content">
							<view class="item-content">
								<view class="item-info">
									<text class="goods-title" @click="goProductDetail(item)">{{ item.goods_name }}</text>
									<view class="goods-spec">
										<text class="spec-text">规格: {{ item.goods_spec }}</text>
										<text class="profit-text">分润: ¥{{ item.huafan }}</text>
									</view>
								</view>

								<view class="item-action">
									<view class="price-info">
										<text class="current-price">￥{{ item.sale_price }}</text>
									</view>

									<view class="quantity-control">
										<view class="quantity-btn minus" :class="{ 'nosubtract': item.is_sale === 0 }"
											@click="decreaseQuantity(item, store)">
											<text class="btn-text">-</text>
										</view>
										<input type="number" :value="item.count" class="quantity-input" readonly />
										<view class="quantity-btn plus" :class="{ 'noadd': item.is_sale === 0 }"
											@click="increaseQuantity(item, store)">
											<text class="btn-text">+</text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>

			<!-- 底部操作栏 -->
			<view class="cart-footer" v-if="!isEditMode">
				<view class="footer-left">
					<view class="select-all" @click="toggleSelectAll">
						<view class="checkbox" :class="{ 'checked': isAllSelected }">
							<image v-if="isAllSelected" :src="serverAddress + 'img/qweqwe.png'" class="checkbox-icon"></image>
						</view>
						<text class="select-text">全选</text>
					</view>
					<view class="total-info">
						<view class="total-price">
							<text class="price-label">合计：</text>
							<text class="price-symbol">¥</text>
							<text class="price-value">{{ totalPrice }}</text>
						</view>
						<view class="profit-info">
							<text class="profit-label">分润：</text>
							<text class="profit-symbol">¥</text>
							<text class="profit-value">{{ totalProfit }}</text>
						</view>
					</view>
				</view>

				<view class="footer-right">
					<button class="checkout-btn" @click="checkout">
						<text class="btn-text">结算（{{ selectedCount }}）</text>
					</button>
				</view>
			</view>

			<!-- 编辑模式底部栏 -->
			<view class="cart-footer" v-else>
				<view class="footer-left">
					<view class="select-all" @click="toggleSelectAll">
						<view class="checkbox" :class="{ 'notall': isAllSelected }">
							<image v-if="isAllSelected" :src="serverAddress + 'img/qweqwe.png'" class="checkbox-icon"></image>
						</view>
						<text class="select-text">全选</text>
					</view>
				</view>

				<view class="footer-right">
					<button class="delete-btn" @click="deleteSelected">
						<text class="btn-text">删除</text>
					</button>
				</view>
			</view>
		</view>

		<!-- 动态底部导航 -->
		<dynamic-tabbar></dynamic-tabbar>
	</view>
</template>

<script>
	import api from '@/api/index.js'
	import {
		getToken,
		getCurrentUser,
		isLoggedIn
	} from '@/api/auth.js'
	import config from '@/api/config.js'
	import DynamicTabbar from '@/components/dynamic-tabbar.vue'
	import {
		inject
	} from 'vue'
	export default {
		components: {
			DynamicTabbar
		},
		data() {
			return {
				serverAddress: inject('$serverAddress', ''),
				isEditMode: false,
			isAllSelected: false,
			loading: false,
			hasNewMessage: false,
			storeGroups: [],
			isLoggedIn: false, // 登录状态
			hasLoaded: false, // 是否已加载过数据
			// 小程序适配相关
			statusBarHeight: 0,
			navBarHeight: 44,
			menuButtonInfo: {},
			windowWidth: 375
			}
		},
		computed: {

			// 所有商品列表（扁平化）
			cartList() {
				let allItems = []
				this.storeGroups.forEach(store => {
					if (store.shop && store.shop.length > 0) {
						allItems = allItems.concat(store.shop)
					}
				})
				console.log('cartList计算属性被调用，结果:', allItems)
				return allItems
			},

			// 选中商品数量
			selectedCount() {
				return this.cartList.filter(item => item.isSelected && !this.isItemInvalid(item)).length
			},

			// 选中商品总价
			totalPrice() {
				let total = 0
				this.cartList.forEach(item => {
					if (item.isSelected && !this.isItemInvalid(item)) {
						total += parseFloat(item.sale_price) * parseInt(item.count)
					}
				})
				return total.toFixed(2)
			},

			// 选中商品总分润
			totalProfit() {
				let total = 0
				this.cartList.forEach(item => {
					if (item.isSelected && !this.isItemInvalid(item)) {
						total += parseFloat(item.huafan) * parseInt(item.count)
					}
				})
				return total.toFixed(2)
			}
		},
		onLoad() {
			this.initMiniProgramAdapt()
			this.checkLoginStatus()
			this.loadCartData()
			this.checkNewMessage()
			this.hasLoaded = true
		},

		onShow() {
			// 页面显示时重新检查登录状态
			const previousLoginStatus = this.isLoggedIn
			this.checkLoginStatus()
			
			// 如果登录状态发生变化（从未登录变为已登录），或者首次加载，才重新加载数据
			if (!this.hasLoaded || (previousLoginStatus !== this.isLoggedIn && this.isLoggedIn)) {
				this.loadCartData()
				this.checkNewMessage()
			}
		},

		onPullDownRefresh() {
			this.loadCartData()
			this.checkNewMessage()
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 1000)
		},

		methods: {
			// 获取图片完整URL
			getImageUrl(path) {
				if (!path) return this.serverAddress + 'static/icon-dianpu@2x.png'
				if (path.startsWith('http')) return path
				if (path.startsWith('/static')) return this.serverAddress + path.substring(1)
				return this.serverAddress + path
			},
		
			// 小程序适配初始化
			initMiniProgramAdapt() {
				// 获取系统信息
				const systemInfo = uni.getSystemInfoSync()
				this.statusBarHeight = systemInfo.statusBarHeight || 0
				this.windowWidth = systemInfo.windowWidth || 375

				// 获取胶囊按钮信息（仅小程序）
				// #ifdef MP
				try {
					this.menuButtonInfo = uni.getMenuButtonBoundingClientRect() || {
						width: 87,
						height: 32,
						top: this.statusBarHeight + 6,
						right: 7,
						bottom: this.statusBarHeight + 38,
						left: this.windowWidth - 94
					}
					this.navBarHeight = this.menuButtonInfo.height + (this.menuButtonInfo.top - this.statusBarHeight) * 2
				} catch (e) {
					console.error('获取胶囊按钮信息失败:', e)
					this.menuButtonInfo = {
						width: 87,
						height: 32,
						top: this.statusBarHeight + 6,
						right: 7,
						bottom: this.statusBarHeight + 38,
						left: this.windowWidth - 94
					}
					this.navBarHeight = 44
				}
				// #endif

				// #ifndef MP
				this.menuButtonInfo = {
					width: 0,
					height: 0,
					top: 0,
					right: 0,
					bottom: 0,
					left: 0
				}
				// #endif
			},
			
			// 检查登录状态
			checkLoginStatus() {
				this.isLoggedIn = isLoggedIn()
			},

			// 检查是否有新消息
			async checkNewMessage() {
				try {
					const result = await api.systemApi.getNotices()
					if (result.r === 0 && result.data.lists) {
						this.hasNewMessage = result.data.lists.some(item => item.num === 1)
					}
				} catch (error) {
					console.error('检查新消息失败:', error)
				}
			},

			// 加载购物车数据
			async loadCartData() {
				try {
					if (!this.isLoggedIn) {
						this.storeGroups = []
						return
					}

					this.loading = true
					uni.showLoading({
						title: '加载中...'
					})

					const result = await api.cartApi.getCartList()

					uni.hideLoading()
					this.loading = false

					if (result.r === 0) {
						const data = result.data

						if (!data || data === '') {
							this.storeGroups = []
							return
						}

						if (!data.list || data.list.length === 0) {
							this.storeGroups = []
							return
						}

						// 处理购物车数据，按原始结构保持
						this.storeGroups = data.list.map(store => ({
							...store,
							isSelected: store.select === 1,
							// 处理商家图片路径（file_path 可能是 null、空字符串或有效路径）
							file_path: (store.file_path && store.file_path !== 'null' && store.file_path.trim() !== '') 
								? (store.file_path.startsWith('http') ? store.file_path : `${config.STATIC_URL}${store.file_path}`)
								: null,
							shop: store.shop.map(item => ({
								...item,
								isSelected: item.select === 1,
								// 处理商品图片路径
								file_path: item.file_path ? (item.file_path.startsWith(
										'http') ? item.file_path :
										`${config.STATIC_URL}${item.file_path}`) :
									'/static/goods-default.png'
							}))
						}))

						console.log('购物车数据处理完成:', this.storeGroups)
						console.log('cartList计算结果:', this.cartList)

						// 设置全选状态
						this.updateAllSelectedState()

					} else {
						console.error('获取购物车数据失败:', result.msg)
						this.storeGroups = []
					}
				} catch (error) {
					uni.hideLoading()
					this.loading = false
					console.error('加载购物车数据失败:', error)
					this.storeGroups = []
				}
			},

			// 判断商品是否失效
			isItemInvalid(item) {
				return item.is_sale === 0 || (item.is_sale === 1 && parseInt(item.count) > parseInt(item.stock))
			},

			// 切换编辑模式
			toggleEditMode() {
				if (!this.isLoggedIn) {
					uni.showToast({
						title: '请登录后编辑',
						icon: 'none'
					})
					return
				}
				this.isEditMode = !this.isEditMode
			},

			// 切换全选
			async toggleSelectAll() {
				const newSelectState = !this.isAllSelected
				this.isAllSelected = newSelectState

				// 获取所有购物车商品ID
				const cartIds = []
				this.cartList.forEach(item => {
					cartIds.push(item.cart_goods_id)
					item.isSelected = newSelectState
				})

				// 更新商家选中状态
				this.storeGroups.forEach(store => {
					store.isSelected = newSelectState
				})

				// 调用API更新选中状态
				try {
					await api.cartApi.selectCartGoods({
						cart_id: cartIds.join(','),
						is_sel: newSelectState ? 1 : 0
					})
					this.computeTotal()
				} catch (error) {
					console.error('更新全选状态失败:', error)
				}
			},

			// 切换商家选中
			async toggleSelectStore(store) {
				const newSelectState = !store.isSelected
				store.isSelected = newSelectState

				// 获取该商家下所有商品ID
				const cartIds = []
				store.shop.forEach(item => {
					cartIds.push(item.cart_goods_id)
					item.isSelected = newSelectState
				})

				// 更新全选状态
				this.updateAllSelectedState()

				// 调用API更新选中状态
				try {
					await api.cartApi.selectCartGoods({
						cart_id: cartIds.join(','),
						is_sel: newSelectState ? 1 : 0
					})
					this.computeTotal()
				} catch (error) {
					console.error('更新商家选中状态失败:', error)
				}
			},

			// 切换商品选中
			async toggleSelectItem(item, store) {
				const newSelectState = !item.isSelected
				item.isSelected = newSelectState

				// 更新商家选中状态
				const storeItems = store.shop.filter(shopItem => !this.isItemInvalid(shopItem))
				if (storeItems.length > 0) {
					store.isSelected = storeItems.every(shopItem => shopItem.isSelected)
				}

				// 更新全选状态
				this.updateAllSelectedState()

				// 调用API更新选中状态
				try {
					await api.cartApi.editCartGoods({
						cart_id: item.cart_goods_id,
						goods_id: item.goods_id,
						spec_id: item.spec_id,
						num: item.count,
						is_sel: newSelectState ? 1 : 0
					})
					this.computeTotal()
				} catch (error) {
					console.error('更新商品选中状态失败:', error)
				}
			},

			// 更新全选状态
			updateAllSelectedState() {
				const validItems = this.cartList.filter(item => !this.isItemInvalid(item))
				this.isAllSelected = validItems.length > 0 && validItems.every(item => item.isSelected)
			},

			// 减少数量
			async decreaseQuantity(item, store) {
				if (item.is_sale === 0) return // 下架商品不可操作

				if (parseInt(item.count) <= 1) {
					uni.showToast({
						title: '该商品不能少于一件',
						icon: 'none'
					})
					return
				}

				const newCount = parseInt(item.count) - 1
				await this.updateItemQuantity(item, store, newCount)
			},

			// 增加数量
			async increaseQuantity(item, store) {
				if (item.is_sale === 0) return // 下架商品不可操作

				const newCount = parseInt(item.count) + 1
				await this.updateItemQuantity(item, store, newCount)
			},

			// 更新商品数量
			async updateItemQuantity(item, store, newCount) {
				try {
					const result = await api.cartApi.editCartGoods({
						cart_id: item.cart_goods_id,
						goods_id: item.goods_id,
						spec_id: item.spec_id,
						num: newCount,
						is_sel: item.isSelected ? 1 : 0
					})

					if (result.r === 0) {
						item.count = result.data.num
						this.computeTotal()

						// 检查库存状态
						if (parseInt(item.count) === parseInt(item.stock)) {
							// 移除缺货状态
							item.is_sale = 1
						}
					} else {
						uni.showToast({
							title: result.msg || '更新失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('更新商品数量失败:', error)
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none'
					})
				}
			},

			// 计算总价和分润
			computeTotal() {
				// 这个方法在computed中已经实现，这里保留是为了兼容原始逻辑
			},

			// 删除选中商品
			async deleteSelected() {
				const selectedItems = this.cartList.filter(item => item.isSelected)
				if (selectedItems.length === 0) {
					uni.showToast({
						title: '您还没有选择商品',
						icon: 'none'
					})
					return
				}

				uni.showModal({
					title: '提示',
					content: '确定要删除选中的商品吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								const cartIds = selectedItems.map(item => item.cart_goods_id)

								uni.showLoading({
									title: '删除中...'
								})

								const result = await api.cartApi.deleteCartGoods({
									cart_id: cartIds.join(',')
								})

								uni.hideLoading()

								if (result.r === 0) {
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									})

									// 重新加载购物车数据
									setTimeout(() => {
										this.loadCartData()
									}, 500)
								} else {
									uni.showToast({
										title: result.msg || '删除失败',
										icon: 'none'
									})
								}
							} catch (error) {
								uni.hideLoading()
								console.error('删除购物车商品失败:', error)
								uni.showToast({
									title: '网络异常，请重试',
									icon: 'none'
								})
							}
						}
					}
				})
			},

			// 结算
			async checkout() {
				// 检查是否登录
				if (!this.isLoggedIn) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					setTimeout(() => {
						this.goLogin()
					}, 1000)
					return
				}

				const selectedItems = this.cartList.filter(item => item.isSelected && !this.isItemInvalid(item))
				if (selectedItems.length === 0) {
					uni.showToast({
						title: '您还没有选择商品',
						icon: 'none'
					})
					return
				}

				// 构建规格ID列表，过滤掉无效的 spec_id
				const specIds = selectedItems
					.map(item => item.spec_id)
					.filter(specId => specId !== undefined && specId !== null && specId !== '')

				if (specIds.length === 0) {
					uni.showToast({
						title: '商品信息不完整，无法结算',
						icon: 'none'
					})
					console.error('结算失败：商品 spec_id 为空', selectedItems)
					return
				}

				// 按店铺分组处理商品数据
				const storeMap = new Map()
				let totalCount = 0
				let totalProfit = 0
				let totalAmount = 0

				// 遍历选中的商品，按店铺分组
				selectedItems.forEach(item => {
					// 找到商品所属的店铺
					const store = this.storeGroups.find(s => 
						s.shop && s.shop.some(shopItem => shopItem.cart_goods_id === item.cart_goods_id)
					)
					
					if (!store) return

					const storeId = store.manufac_id || store.id || Date.now()
					
					if (!storeMap.has(storeId)) {
						storeMap.set(storeId, {
							id: storeId,
							name: store.manufac_name || store.name || '未知店铺',
							logo: store.file_path || null,
							goods: [],
							totalProfit: 0
						})
					}

					const storeData = storeMap.get(storeId)
					const quantity = parseInt(item.count) || 1
					const price = parseFloat(item.sale_price) || 0
					const profit = parseFloat(item.huafan) || 0

					storeData.goods.push({
						id: item.goods_id,
						name: item.goods_name,
						image: item.file_path || '/static/goods-default.png',
						spec: item.goods_spec || '规格:默认',
						price: price,
						profit: profit,
						quantity: quantity
					})

					storeData.totalProfit += profit * quantity
					totalCount += quantity
					totalProfit += profit * quantity
					totalAmount += price * quantity
				})

				// 转换为数组格式
				const storeList = Array.from(storeMap.values())


				// 跳转到确认订单页面
				try {
					uni.navigateTo({
						url: `/pages/order/confirm?spec_id=${specIds.join(',')}&count=&source=2&select=${this.isAllSelected ? 1 : 0}`,
						fail: (err) => {
							console.error('跳转确认订单页面失败:', err)
							uni.showToast({
								title: '跳转失败，请重试',
								icon: 'none'
							})
						}
					})
				} catch (error) {
					console.error('结算跳转错误:', error)
					uni.showToast({
						title: '结算失败，请重试',
						icon: 'none'
					})
				}
			},

			// 跳转商品详情
			goProductDetail(item) {
				uni.navigateTo({
					url: `/pages/goods/detail?goodsid=${item.goods_id}`
				})
			},

			// 返回上一页
			goBack() {
				uni.navigateBack()
			},

			// 跳转消息页面
			goMessage() {
				if (!this.isLoggedIn) {
					uni.navigateTo({
						url: '/pages/login/index'
					})
				} else {
					uni.navigateTo({
						url: '/pages/news/index'
					})
				}
			},

			// 跳转登录页面
			goLogin() {
				uni.navigateTo({
					url: '/pages/login/login?redirect=/pages/cart/index'
				})
			},

			// 去购物
			goShopping() {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			},

			// 处理Logo加载错误
			handleLogoError(e, store) {
				// 如果加载失败，设置为 null，显示默认图标
				store.file_path = null
			}
		}
	}
</script>

<style lang="scss" scoped>
	.cart-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-top: calc(var(--status-bar-height, 0px) + 44px);
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
	}

	// 自定义导航栏样式
	.custom-navbar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;
		background: linear-gradient(135deg, #FF8033 0%, #FF6B35 100%);
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);

		.navbar-content {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 30rpx 0 30rpx;
			position: relative;
			height: 100%;

			.navbar-title {
				display: flex;
				align-items: center;
				justify-content: flex-start;
				height: 100%;

				.title-text {
					color: #fff;
					font-size: 42rpx;
					font-weight: 600;
					letter-spacing: 1rpx;
					line-height: 1;
				}
			}

			.navbar-right {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				margin-left: auto;
				height: 100%;
				transform: translateX(-20rpx);

				.edit-btn {
					margin-right: 16rpx;
					padding: 8rpx 12rpx;
					background-color: rgba(255, 255, 255, 0.9);
					border-radius: 20rpx;
					min-width: 60rpx;
					text-align: center;
					box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
					display: flex;
					align-items: center;
					justify-content: center;

					.edit-text {
						font-size: 26rpx;
						color: #333;
						font-weight: 500;
						line-height: 1;
					}
				}

				.message-btn {
					width: 64rpx;
					height: 64rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					position: relative;

					.message-dot {
						position: absolute;
						top: 12rpx;
						right: 12rpx;
						width: 16rpx;
						height: 16rpx;
						background-color: #ff4757;
						border-radius: 50%;
						border: 2rpx solid #fff;
					}
				}
			}
		}
	}

	// 空购物车
	.empty-cart {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;

		.empty-content {
			text-align: center;
			display: flex;
			flex-direction: column;

			.empty-text {
				font-size: 44rpx;
				color: #666666;
				margin-bottom: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.login-link {
				color: #FF8033;
				margin-left: 0;
			}

			.empty-desc {
				font-size: 28rpx;
				color: #8b8b8b;
				margin-bottom: 60rpx;
			}

			.go-shopping-btn {
				width: 320rpx;
				height: 80rpx;
				background-color: #ff9600;
				border-radius: 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border: none;

				.btn-text {
					color: #fff;
					font-size: 32rpx;
				}
			}
		}
	}

	// 购物车内容
	.cart-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		margin-top: 40rpx;
		height: 0;
		overflow: hidden;
	}

	.cart-scroll {
		flex: 1;
		height: 0;
		padding-bottom: 200rpx;
		box-sizing: border-box;
	}

	// 商家分组
	.store-group {
		background-color: #fff;
		margin-bottom: 20rpx;
	}

	.store-header {
		height: 100rpx;
		display: flex;
		align-items: center;
		padding: 0 30rpx;

		.store-select {
			margin-right: 20rpx;
		}

		.store-info {
			display: flex;
			align-items: center;
			flex: 1;

			.store-logo,
			.store-logo-default {
				width: 60rpx;
				height: 60rpx;
				border-radius: 8rpx;
				margin-right: 24rpx;
				flex-shrink: 0;
			}

			.store-name {
				font-size: 28rpx;
				color: #333;
				font-weight: 500;
			}
		}
	}

	// 商品项
	.goods-item {
		display: flex;
		border-bottom: 1px solid #f5f5f5;
		min-height: 200rpx;
		background-color: #fff;
		align-items: flex-start; // 确保顶部对齐

		&.inshort {
			opacity: 0.6;
		}

		// 左侧固定层
		.item-left-layer {
			width: 242rpx; // 固定宽度：42rpx(选择框) + 20rpx(间距) + 160rpx(图片) + 20rpx(间距)
			flex-shrink: 0; // 防止被压缩，这是关键！
			display: flex;
			align-items: center;
			padding: 30rpx 0 30rpx 30rpx;
			background-color: #fff;
			// border-right: 1px solid #f5f5f5; // 添加右边框分隔

			.item-select {
				width: 42rpx;
				margin-right: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.item-photo {
				width: 160rpx;
				position: relative;

				.goods-image {
					width: 160rpx;
					height: 160rpx;
					border-radius: 8rpx;
					object-fit: cover;
				}

				.status-tag {
					position: absolute;
					top: 0;
					left: 0;
					background-color: rgba(0, 0, 0, 0.6);
					color: #fff;
					font-size: 24rpx;
					padding: 4rpx 8rpx;
					border-radius: 4rpx;
				}
			}
		}

		// 右侧内容区域
		.item-right-content {
			flex: 1; // 占据剩余空间
			min-width: 0; // 允许内容收缩，防止溢出
			padding: 30rpx 30rpx 30rpx 20rpx;
			background-color: #fff;

			.item-content {
				height: 100%;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				min-height: 140rpx; // 最小高度

				.item-info {
					flex: 1;
					margin-bottom: 20rpx;

					.goods-title {
						font-size: 28rpx;
						color: #333;
						font-weight: bold;
						line-height: 1.4;
						word-wrap: break-word; // 长文本换行
						word-break: break-all; // 强制换行，防止溢出
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
						overflow: hidden;
						margin-bottom: 12rpx;
					}

					.goods-spec {
						display: flex;
						align-items: flex-start;
						justify-content: flex-start;
						margin-bottom: 12rpx;
						flex-wrap: wrap;

						.spec-text {
							font-size: 26rpx;
							color: #9c9c9c;
							word-wrap: break-word;
							word-break: break-all;
							line-height: 1.3;
						}

						.profit-text {
							font-size: 26rpx;
							color: #FF8033;
							white-space: nowrap;
							margin-left: 10rpx;
						}
					}
				}

				.item-action {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: auto; // 推到底部
					flex-wrap: wrap; // 允许换行
					gap: 10rpx;

					.price-info {
						flex-shrink: 0; // 不压缩

						.current-price {
							font-size: 30rpx;
							color: #ff4757;
							font-weight: 500;
							white-space: nowrap;
						}
					}

					.quantity-control {
						display: flex;
						align-items: center;
						flex-shrink: 0; // 不压缩

						.quantity-btn {
							width: 56rpx;
							height: 56rpx;
							border: 1px solid #ddd;
							display: flex;
							align-items: center;
							justify-content: center;
							background-color: #fff;

							&.minus {
								border-radius: 8rpx 0 0 8rpx;

								&.nosubtract {
									opacity: 0.3;
								}
							}

							&.plus {
								border-radius: 0 8rpx 8rpx 0;

								&.noadd {
									opacity: 0.3;
								}
							}

							.btn-text {
								font-size: 32rpx;
								color: #333;
							}
						}

						.quantity-input {
							width: 80rpx;
							height: 56rpx;
							text-align: center;
							font-size: 28rpx;
							color: #333;
							border-top: 1px solid #ddd;
							border-bottom: 1px solid #ddd;
							background-color: #fff;
						}
					}
				}
			}
		}
	}

	// 复选框样式
	.checkbox {
		width: 42rpx;
		height: 42rpx;
		border: 2rpx solid #ddd;
		border-radius: 50%;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: transparent;

		&.checked {
			background-color: #FF8033;
			border-color: #FF8033;
		}

		&.gchecked,
		&.notall {
			background-color: #FF8033;
			border-color: #FF8033;
		}

		&.inshort {
			opacity: 0.3;
		}

		.checkbox-icon {
			width: 42rpx;
			height: 42rpx;
			border-radius: 50%;
		}
	}

	// 底部操作栏
	.cart-footer {
		position: fixed;
		bottom: 100rpx;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: #fff;
		border-top: 1px solid #eee;
		display: flex;
		align-items: center;
		padding: 0 0 0 30rpx;
		padding-bottom: env(safe-area-inset-bottom);
		z-index: 999;

		.footer-left {
			display: flex;
			align-items: center;
			flex: 1;

			.select-all {
				display: flex;
				align-items: center;
				margin-right: 30rpx;

				.select-text {
					font-size: 26rpx;
					color: #666666;
					margin-left: 16rpx;
				}
			}

			.total-info {
				display: flex;
				flex-direction: column;
				justify-content: center;

				.total-price {
					display: flex;
					align-items: baseline;
					margin-bottom: 4rpx;

					.price-label {
						font-size: 26rpx;
						color: #666666;
					}

					.price-symbol {
						font-size: 22rpx;
						color: #FF4242;
					}

					.price-value {
						font-size: 30rpx;
						color: #FF4242;
						font-weight: bold;
					}
				}

				.profit-info {
					display: flex;
					align-items: baseline;

					.profit-label {
						font-size: 22rpx;
						color: #999999;
					}

					.profit-symbol {
						font-size: 20rpx;
						color: #FF8033;
					}

					.profit-value {
						font-size: 22rpx;
						color: #FF8033;
					}
				}
			}
		}

		.footer-right {
			.checkout-btn {
				width: 220rpx;
				height: 100rpx;
				background-color: #FF4242;
				border-radius: 0;
				display: flex;
				align-items: center;
				justify-content: center;
				border: none;
				margin: 0;

				.btn-text {
					color: #fff;
					font-size: 30rpx;
				}
			}

			.delete-btn {
				width: 220rpx;
				height: 60rpx;
				background-color: #ff9600;
				border-radius: 30rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border: none;

				.btn-text {
					color: #fff;
					font-size: 30rpx;
				}
			}
		}
	}
</style>